<?php

namespace common\sms\yuexin;

use Cm;
use common\models\CmDataModel;
use yii\db\Expression;

class Yuexin
{
    /**
     * @var AuthCode
     */
    public $authCode;

    function __construct()
    {
        $this->authCode = new AuthCode($this);
    }

    function batchSend($communityID, $content,$telsArr, &$error = '')
    {
        $config = \Yii::$app->params['sms']['yuexin'];
        $content = "【{$config['signname']}】{$content}";

        $tels = [];
        $index = 0;
        foreach ($telsArr as $u) {
            if (empty($u['tel']))
                continue;
            if (!isset($tels[$index]))
                $tels[$index][] = $u['tel'];
            else {
                $tels[$index][] = $u['tel'];
                if (count($tels[$index]) == 100) {
                    $index++;
                    $tels[$index][] = $u['tel'];
                }
            }
        }

        foreach ($tels as $t) {
            $this->send(implode(',', $t), $content, 1, $communityID, $error);
        }
    }

    public function send($tels, $content, $type = 0, $communityID = 0, &$error = '')
    {
        $tels = ltrim($tels, ',');
        $tels = rtrim($tels, ',');

        $info = Cm::$db->one("select sms_remain from community where id={$communityID}");
        $smsRemain = isset($info['sms_remain']) ? $info['sms_remain'] : 0;

        $numTel = count(explode(',', $tels));
        $contentLen = mb_strlen($content, "utf-8");
        $numSms = $contentLen <= 70 ? 1 : (ceil($contentLen / 67));
        $numTotalSms = $numSms * $numTel;

        $flag = false;
        $post_data = [];
        $res = '';
        $OutId = (new CmDataModel())->number();
        $resID = '';
        try {

            if (($communityID > 0 && $numTotalSms <= $smsRemain) || !$communityID) {
                $config = \Yii::$app->params['sms']['yuexin'];
                $accessKeyId = $config['id'];
                $accessKeySecret = $config['key'];
                $url = $config['url'];
                $mttime = date("YmdHis");
                $name = $accessKeyId;//开通的用户名
                $password = $accessKeySecret;//密码
                $post_data['name'] = $name;
                $post_data['pwd'] = md5($password . $mttime);
                $post_data['content'] = $content;
                //$post_data['content'] = '123456'; 语音验证码内容
                $post_data['phone'] = $tels;//手机号码
                $post_data['subid'] = '';
                $post_data['mttime'] = $mttime;
                $post_data['rpttype'] = '1';
                $o = "";
                foreach ($post_data as $k => $v) {
                    $o .= "$k=" . urlencode($v) . "&";
                }
                $pdata = substr($o, 0, -1);
                $res = \Cm::$curl->post($url, $pdata);

                $resArr = json_decode($res, true);

                $state = isset($resArr['ReqCode']) ? (int)$resArr['ReqCode'] : -1;
                $msg = isset($resArr['ReqMsg']) ? $resArr['ReqMsg'] : '';
                $resID = isset($resArr['ReqId']) ? $resArr['ReqId'] : '';
                if ($state === 0) {
                    $flag = true;
                } else
                    $error = $msg;
            }

            if (($communityID > 0 && $numTotalSms > $smsRemain))
                $error = '社区短信条数可用量不足';

        } catch (\yii\console\Exception $e) {
            $error = $e->getMessage();
        }


        $logData = [
            "community_id" => $communityID,
            "number" => $OutId,
            "type" => $type,//0：验证码；1：社区群发；2：充值；3：社区单发
            'tel' => $tels,
            'tel_num' => $numTel,
            "content" => $content,
            'content_len' => $contentLen,
            "total" => $numSms,
            "req_data" => json_encode($post_data),
            "res_id" => $resID,
            "res_data" => $res,
            "res_status" => $flag ? 1 : 0,
            "res_error" => $error ? $error : '',
            "addtime" => date('Y-m-d H:i:s')
        ];
        $id = Cm::$db->insert('sms_log', $logData);
        if ($communityID && $flag) {
            Cm::$db->update('community', ['sms_remain' => new Expression("sms_remain-{$numTotalSms}")], "id={$communityID}");
        }
        return $flag;
    }

    public function getStateMsg($key)
    {
        $arr = [
            "0" => "发送成功",
            "JL:0002" => "手机号异常 手机号码不正确等",
            "JL:0003" => "扩展码超长",
            "JL:0013" => "用户上行退订黑名单",
            "JL:0014" => "短信内容中有违禁词",
            "JL:0015" => "帐号余额不足",
            "JL:0016" => "帐号日发送上限",
            "JL:0017" => "通道未配置 需联系客服配置通道",
            "JL:0018" => "短信提交超速 默认限制 100 次／秒",
            "JL:0019" => "余额查询超速 默认限制 1 次／分钟",
            "JL:0020" => "状态报告主动查询超速 默认限制 1 次／秒",
            "JL:0021" => "群发限制 默认 20:00 点到第二天 7:00 点前不允许群发短信",
            "JL:0022" => "短信签名未备案",
            "JL:0023" => "短信签名未设置或设置错误",
            "JL:0024" => "关键字或群发审核未通过",
            "JL:0025" => "单个号码日发送上限",
            "JL:0026" => "投诉黑名单",
            "JL:0028" => "黑名单",
            "JL:0029" => "无签名拦截",
            "JL:0030" => "号码相同内容流速控制",
            "JL:0031" => "号码内容关键字流速控制",
            "JL:0032" => "号码默认流速控制",
            "JL:0033" => "关键字策略拦截"
        ];
        return isset($arr[$key]) ? $arr[$key] : '未知错误';
    }

    public function info()
    {

    }
}

class AuthCode
{
    private $sessionKey = 'sms-code2';

    private $api = null;

    function __construct($api)
    {
        $this->api = $api;
    }

    function send($tel, &$error = '')
    {
        $flag = false;
        try {
            $code = mt_rand(1000, 9999);
            $config = \Yii::$app->params['sms']['yuexin'];
            $content = "【{$config['signname']}】尊敬的用户：您的校验码：{$code}，工作人员不会索取，请勿泄漏。";

            $flag = $this->api->send($tel, $content, 0, 0, $error);

            if ($flag)
                \Yii::$app->session->set($this->sessionKey, ["tel" => $tel, "code" => $code]);

        } catch (\yii\console\Exception $e) {
            $error = $e->getMessage();
        }

        return $flag;
    }

    function check($tel, $code)
    {
        $data = \Yii::$app->session->get($this->sessionKey);
        $_tel = isset($data['tel']) ? $data['tel'] : '';
        $_code = isset($data['code']) ? $data['code'] : '';
        if ($tel == $_tel && $_code == $code)
            return true;
        return false;
    }
}